import React, { useState, useEffect } from 'react';
import { Box, Divider, Drawer, AppBar, Toolbar, Typography, IconButton, List, ListItem, ListItemIcon, ListItemText, CssBaseline, Chip } from '@mui/material';
import { Menu, ChevronLeft, Dashboard, Logout, DataUsage, Map, Public, NetworkCheck, AdminPanelSettings, DirectionsCar, Warning, Build, Assignment } from '@mui/icons-material';
import { Outlet, useNavigate, useLocation } from 'react-router-dom';
import { apiRequest } from '../utils/api';

const drawerWidth = 240;

const DashboardLayout = () => {
  const [mobileOpen, setMobileOpen] = useState(false);
  const [userInfo, setUserInfo] = useState(null);
  const navigate = useNavigate();
  const location = useLocation();

  useEffect(() => {
    // 获取用户信息
    const getUserInfo = () => {
      try {
        const info = localStorage.getItem('userInfo');
        return info ? JSON.parse(info) : null;
      } catch (error) {
        console.error('Failed to parse user info:', error);
        return null;
      }
    };

    const user = getUserInfo();
    setUserInfo(user);

    // 检查用户是否已登录
    const token = localStorage.getItem('token');
    if (!token && window.location.pathname !== '/login' && window.location.pathname !== '/register') {
      navigate('/login');
    }
    
    // 为服务商添加强制重定向逻辑
    if (user?.role === 'SERVICE_PROVIDER') {
      // 检查当前路径是否已经是服务商相关路径
      const isServiceProviderPath = window.location.pathname.startsWith('/service-provider');
      if (!isServiceProviderPath) {
        navigate('/service-provider/attributes');
      }
    }
  }, [navigate]);

  const handleDrawerToggle = () => {
    setMobileOpen(!mobileOpen);
  };

  const handleLogout = async () => {
    try {
      console.log('Sending logout request to:', '/api/auth/logout');
      await apiRequest.post('/api/auth/logout');
      console.log('Logout successful');
    } catch (err) {
      console.error('Logout error:', err);
    } finally {
      localStorage.removeItem('token');
      localStorage.removeItem('userInfo');
      setTimeout(() => {
        navigate('/login');
      }, 100);
    }
  };

  const getMenuItems = () => {
    if (userInfo?.role === 'ADMIN') {
      return [
        { text: '仪表板', icon: <Dashboard />, path: '/dashboard' },
        { text: '维修数据', icon: <DataUsage />, path: '/vehicle-data' },
        { text: '历史轨迹', icon: <Map />, path: '/track-history' },
        { text: '公共数据', icon: <Public />, path: '/public-data' },
        { text: '紧急警报', icon: <Warning />, path: '/emergency-alerts' },
        { text: '维修管理', icon: <Build />, path: '/maintenance-records' },
        { text: '全部车辆', icon: <DirectionsCar />, path: '/vehicles' },
        { text: '车联网', icon: <NetworkCheck />, path: '/vehicle-networking' },
        { text: '管理员控制台', icon: <AdminPanelSettings />, path: '/admin/dashboard' }
      ];
    }

    if (userInfo?.role === 'SERVICE_PROVIDER') {
      return [
        { text: '属性栏', icon: <NetworkCheck />, path: '/service-provider/attributes' },
        { text: '用户文件栏', icon: <DataUsage />, path: '/service-provider/user-files' },
        { text: '信息展示栏', icon: <Assignment />, path: '/service-provider/info-display' }
      ];
    }

    // 普通用户
    return [
      { text: '仪表板', icon: <Dashboard />, path: '/dashboard' },
      { text: '数据管理', icon: <DataUsage />, path: '/vehicle-data' },
      { text: '轨迹记录', icon: <Map />, path: '/track-history' },
      { text: '公共数据', icon: <Public />, path: '/public-data' },
      { text: '维修记录', icon: <Build />, path: '/maintenance-records' },
      { text: '车联网', icon: <NetworkCheck />, path: '/vehicle-networking' }
    ];
  };

  const menuItems = getMenuItems();

  // 检查是否为当前路径
  const isActive = (path) => {
    // 处理根路径和精确匹配
    if (path === '/') {
      return location.pathname === '/';
    }
    // 处理子路径匹配
    return location.pathname === path || location.pathname.startsWith(path + '/');
  };

  const drawer = (
    <div>
      <Toolbar sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', px: [1] }}>
        <Typography variant="h6" noWrap sx={{ fontSize: '1rem' }}>
          车辆安全系统
        </Typography>
        <IconButton onClick={handleDrawerToggle}>
          <ChevronLeft />
        </IconButton>
      </Toolbar>
      <Divider />
      <List>
        {menuItems.map((item) => (
          <ListItem 
            button="true" 
            key={item.text} 
            onClick={() => navigate(item.path)}
            sx={{
              backgroundColor: isActive(item.path) ? 'primary.main' : 'transparent',
              color: isActive(item.path) ? 'primary.contrastText' : 'inherit',
              borderRadius: 1,
              mx: 1,
              my: 0.5,
              cursor: 'pointer',
              '&:hover': {
                backgroundColor: isActive(item.path) ? 'primary.dark' : 'action.hover',
                cursor: 'pointer',
              },
              '& .MuiListItemIcon-root': {
                color: isActive(item.path) ? 'primary.contrastText' : 'inherit',
              },
              transition: 'all 0.2s ease-in-out',
            }}
          >
            <ListItemIcon>{item.icon}</ListItemIcon>
            <ListItemText primary={item.text} />
          </ListItem>
        ))}
      </List>
      <Divider sx={{ mt: 'auto' }} />
      <List>
        <ListItem 
          button="true" 
          onClick={handleLogout} 
          sx={{ 
            color: 'error.main',
            borderRadius: 1,
            mx: 1,
            cursor: 'pointer',
            '&:hover': {
              backgroundColor: 'action.hover',
              cursor: 'pointer',
            },
            transition: 'all 0.2s ease-in-out',
          }}
        >
          <ListItemIcon><Logout sx={{ color: 'error.main' }} /></ListItemIcon>
          <ListItemText primary="退出登录" />
        </ListItem>
      </List>
    </div>
  );

  return (
    <Box sx={{ display: 'flex' }}>
      <CssBaseline />
      <AppBar
        position="fixed"
        sx={{
          width: { sm: `calc(100% - ${drawerWidth}px)` },
          ml: { sm: `${drawerWidth}px` },
        }}
      >
        <Toolbar sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <IconButton
              color="inherit"
              aria-label="open drawer"
              edge="start"
              onClick={handleDrawerToggle}
              sx={{ mr: 2, display: { sm: 'none' } }}
            >
              <Menu />
            </IconButton>
          </div>
          {userInfo && (
            <Box sx={{ display: 'flex', alignItems: 'center', gap: 2 }}>
              <Chip 
                label={userInfo.role} 
                color={userInfo.role === 'ADMIN' ? 'error' : 'primary'}
                size="small"
                variant="outlined"
              />
              <Typography variant="subtitle1" color="inherit" noWrap>
                {userInfo.firstName} {userInfo.lastName}
              </Typography>
            </Box>
          )}
        </Toolbar>
      </AppBar>
      <Box
        component="nav"
        sx={{ width: { sm: drawerWidth }, flexShrink: { sm: 0 } }}
        aria-label="mailbox folders"
      >
        <Drawer
          variant="temporary"
          open={mobileOpen}
          onClose={handleDrawerToggle}
          ModalProps={{ keepMounted: true }}
          sx={{
            display: { xs: 'block', sm: 'none' },
            '& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth },
          }}
        >
          {drawer}
        </Drawer>
        <Drawer
          variant="permanent"
          sx={{
            display: { xs: 'none', sm: 'block' },
            '& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth },
          }}
          open
        >
          {drawer}
        </Drawer>
      </Box>
      <Box
        component="main"
        sx={{
          flexGrow: 1,
          p: 3,
          width: { sm: `calc(100% - ${drawerWidth}px)` },
        }}
      >
        <Toolbar />
        <Outlet />
      </Box>
    </Box>
  );
};

export default DashboardLayout;